const express = require('express');
const router = express.Router();
const axios = require("axios");
const { v4: uuidv4 } = require('uuid');
const { Order } = require("../../db");


// 配置
const CONFIG = {
    // 商户id
    MCH_ID: '1601784331',
    // 云托管环境ID
    ENV_ID: "prod-1g8v9z3sa56f8be6",
    // 云托管服务名
    SERVICE_NAME: "express-ikbx"
}

// 小程序调用，获取微信 Open ID
router.get("/wx_openid", async (req, res) => {
    if (req.headers["x-wx-source"]) {
        res.send(req.headers["x-wx-openid"]);
    }
});

// 接受微信回调
router.post("/pay/callback", async (req, res) => {
    // if (req.headers["x-wx-source"]) {
    //   // res.send(req.headers["x-wx-openid"]);
    // }
    console.log('收到微信支付回调', req.body);
    let body = req.body;
    if (body.returnCode == 'SUCCESS') {
        const orderDb = await Order.findOne({ where: { order_no: body.outTradeNo } });
        if (orderDb.status == 2) {
            res.end();
            return;
        }

        // 更新
        await orderDb.update({
            status: 2,
            cash_fee: body.cashFee,
            wx_trade_no: body.transactionId,
            pay_success_time: new Date()
        }, {
            where: {
                id: orderDb.id
            }
        });
    }

    res.send({ "errcode": 0 });
});


// 微信侧查询订单
router.post("/pay/queryWx", async (req, res) => {
    const body = req.body;

    if (!body.orderNo) {
        res.send({
            success: false,
            msg: '订单号不能为空'
        })
        return;
    }

    axios.post('http://api.weixin.qq.com/_/pay/queryorder', {
        out_trade_no: body.orderNo,
        sub_mch_id: CONFIG.MCH_ID
    }).then(resp => {
        res.send({
            success: true,
            data: resp.data
        });
    })
})


// 对外查询订单
router.post("/pay/query", async (req, res) => {
    const body = req.body;

    if (!body.orderNo) {
        res.send({
            success: false,
            msg: '订单号不能为空'
        })
        return;
    }

    const orderDb = await Order.findOne({ where: { order_no: body.orderNo } });
    if (orderDb == null) {
        res.send({
            success: false,
            msg: '订单不存在'
        })
        return;
    }

    res.send({
        success: true,
        data: {
            orderNo: orderDb.order_no,
            tradeNo: orderDb.out_trade_no,
            status: orderDb.status,
            totalFee: orderDb.total_fee,
            cashFee: orderDb.cash_fee
        }
    });
});



// 获取支付产品名称
function getProductName(totalFee) {
    return (totalFee / 100) + '元';
}


// 创建订单
router.post("/pay/create", async (req, res) => {
    let ip = req.headers["x-forwarded-for"] || '127.0.0.1';
    const body = req.body;

    const orderDb = await Order.findOne({ where: { out_trade_no: body.tradeNo } });
    if (orderDb != null) {
        res.send({
            success: false,
            msg: '订单已存在'
        })
        return;
    }

    // 生成订单号
    let orderNo = (uuidv4().replace(/-/g, ''));
    const order = await Order.create({
        mch_id: body.mchId,
        order_no: orderNo,
        out_trade_no: body.tradeNo,
        total_fee: body.fee,
        status: 0,
        create_time: new Date()
    });

    console.log('商户下单', order, ip);

    let generateUrlParam = {
        path: 'pages/order',
        query: `orderNo=${orderNo}`,
        expire_type: '0',
        expire_time: new Date().getTime() + (1000 * 60 * 10)
    };
    // 生成小程序码
    axios.post('https://api.weixin.qq.com/wxa/generate_urllink', generateUrlParam).then(resp => {
        console.log('生成小程序链接返回:', generateUrlParam, resp.data);
        res.send({
            success: true,
            data: {
                orderNo: orderNo,
                payUrl: resp.data.url_link
            }
        });
    })

})

// 拉起支付
router.post("/pay/unifiedorder", async (req, res) => {
    let ip = req.headers["x-forwarded-for"] || '127.0.0.1';

    const body = req.body;
    const order = await Order.findOne({ where: { order_no: body.orderNo } });
    console.log('小程序用户支付 参数', body, order, ip);
    if (order === null) {
        res.end();
        return;
    }

    if (order.status == 1) {
        res.send(order.trade_param);
        return;
    }

    if (order.status == 2) {
        res.send({
            success: false,
            msg: '订单已经支付成功'
        });
        return;
    }

    if (order.status == 3 || (order.status == 4)) {
        res.send({
            success: false,
            msg: '支付失败'
        });
        return;
    }

    let url = 'http://api.weixin.qq.com/_/pay/unifiedorder';
    if (req.headers["x-wx-source"]) {
        req.headers["x-wx-openid"];
    }

    const openId = req.headers["x-wx-openid"];

    // 支付参数
    let payParam = {
        "openid": openId,
        "body": getProductName(order.total_fee),
        "out_trade_no": order.order_no,
        "spbill_create_ip": ip,
        "sub_mch_id": CONFIG.MCH_ID,
        "total_fee": order.total_fee,
        "env_id": CONFIG.ENV_ID,
        "callback_type": 2,
        "container": {
            "service": CONFIG.SERVICE_NAME,
            "path": "/api/pay/callback"
        }
    };

    // 发起微信支付
    axios.post(url, payParam).then(async resp => {
        console.log('微信支付参数：', payParam, '返回：', resp.data);
        if (resp.data.errcode != 0) {
            res.send({
                status: 0,
                msg: '支付失败'
            });
            return;
        }
        let param = resp.data.respdata.payment;

        // 更新订单信息
        await order.update({
            status: 1,
            user_open_id: openId,
            pay_user_ip: ip,
            trade_param: JSON.stringify(param),
            launch_pay_time: new Date()
        }, {
            where: {
                id: order.id
            }
        });

        res.send(param)
    });
});


module.exports = router;